/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.app.mockexam.theory.record.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.modules.conf.RedisUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.app.mockexam.special.record.entity.AppMockexamSpecialRecord;
import com.jeesite.modules.app.mockexam.theory.entity.AppExaminateTheory;
import com.jeesite.modules.app.mockexam.theory.record.entity.AppMockexamTheoryRecord;
import com.jeesite.modules.app.mockexam.theory.record.service.AppMockexamTheoryRecordService;
import com.jeesite.modules.app.mockexam.theory.service.AppExaminateTheoryService;
import com.jeesite.modules.app.mockexam.theory.user.entity.TmockexamTheoryUser;
import com.jeesite.modules.app.mockexam.theory.user.service.TmockexamTheoryUserService;
import com.jeesite.modules.app.util.answer.AnswerUtils;
import com.jeesite.modules.conf.AppController;
import com.jeesite.modules.conf.MessageCode;
import com.jeesite.modules.zx.mockexam.theory.entity.TmockexamTheory;
import com.jeesite.modules.zx.mockexam.theory.service.TmockexamTheoryService;
import com.jeesite.modules.zx.question.bank.entity.TquestionBank;
import com.jeesite.modules.zx.question.bank.service.TquestionBankService;

/**
 * 模拟理论考试记录Controller
 * @author zpp
 * @version 2020-02-10
 */
@Controller
@RequestMapping(value = "/app/mockexam/theory/record/")
public class AppMockexamTheoryRecordController{

	@Autowired
	private AppMockexamTheoryRecordService appMockexamTheoryRecordService;
	@Autowired
	private TmockexamTheoryUserService tmockexamTheoryUserService;
	@Autowired
	private TmockexamTheoryService tmockexamTheoryService;
	@Autowired
	private TquestionBankService tquestionBankService;
	@Autowired
	private RedisUtils redisUtils;
	/**
	 * 多选题
	 * @param entity
	 * @param request
	 * @param response
	 */
	@RequestMapping(value ="addmul")
	public void addmul(AppMockexamTheoryRecord entity, HttpServletRequest request,HttpServletResponse response){
		String theoryId = entity.getTheoryId();
		if(StringUtils.isBlank(theoryId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"理论标识不存在");
			return;
		}
		String questionId = entity.getQuestionId();
		if(StringUtils.isBlank(questionId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"问题标识不存在");
			return;
		}
		Integer questionType = entity.getQuestionType();
		if(questionType==null){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"问题类型不存在");
			return;
		}
		String userId = entity.getUserId();
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"用户信息");
			return;
		}
		String answerId = entity.getAnswerId();
		String[] split = answerId.split(",");
        List<String> list=new ArrayList<String>();
        for(String key:split){
       	 if(StringUtils.isNotBlank(key)){
       		 list.add(key);
       	 }
        }
		if(StringUtils.isBlank(answerId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"答案信息");
			return;
		}
		AppMockexamTheoryRecord model=new AppMockexamTheoryRecord();
		model.setTheoryId(theoryId);
		model.setQuestionId(questionId);
		model.setUserId(userId);
		List<AppMockexamTheoryRecord> findList = appMockexamTheoryRecordService.findList(model);
		String id="";
		if(findList!=null&&findList.size()>0){
			id=findList.get(0).getId();
		}
		TmockexamTheory answerObj = new TmockexamTheory();
		answerObj.setParentCode(questionId);
		answerObj.setObjAnswer("1");		
		List<TmockexamTheory> findList2 = tmockexamTheoryService.findList(answerObj);
		int a=list.size();
		int b=findList2.size();
		if(a==b){
			boolean flag=true;
			for(TmockexamTheory ans:findList2){
				String ansId=ans.getId();
				if(!list.contains(ansId)){
					flag=false;
				}
			}
			if(flag){
				TmockexamTheory scorObje=tmockexamTheoryService.get(questionId);
				BigDecimal score = scorObje.getScore();
				entity.setScore(score);
			}else{
				entity.setScore(new BigDecimal(0.0));
			}
		}else{
			entity.setScore(new BigDecimal(0.0));
		}
		if(StringUtils.isNotBlank(id)){
			entity.setId(id);
			appMockexamTheoryRecordService.update(entity);
		}else{
			appMockexamTheoryRecordService.save(entity);
		}
		JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(entity));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	}
	@PostMapping(value = "saveRecord")
	public void saveRecord(AppMockexamTheoryRecord entity,HttpServletRequest request,HttpServletResponse response) {
		String theoryId = entity.getTheoryId();
		if(StringUtils.isBlank(theoryId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"理论标识不存在");
			return;
		}
		String questionId = entity.getQuestionId();
		if(StringUtils.isBlank(questionId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"问题标识不存在");
			return;
		}
		Integer questionType = entity.getQuestionType();
		if(questionType==null){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"问题类型不存在");
			return;
		}
         String userId=entity.getUserId();		// 用户主键
         if(StringUtils.isBlank(userId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			 return;
		 }
		 String answerId=entity.getAnswerId();		// 答案字段
         if(StringUtils.isBlank(answerId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "答案信息");
			 return;
		 }
         String postId=entity.getPostId();
         if(StringUtils.isBlank(postId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "试卷标识");
			 return;
         }

		TquestionBank answerObj = null;
         String questionIdKey = theoryId+"-"+questionId;
		if (redisUtils.hasKey(questionIdKey)){
			answerObj = (TquestionBank) redisUtils.get(questionIdKey);
		}else{
			answerObj = tquestionBankService.get(questionId);
			redisUtils.set(questionIdKey,answerObj);
		}
		if(answerObj==null){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "问题数据不存在");
			return;
		}
		String objAnswer = answerObj.getObjAnswer();

		//当前用户当前题的记录
		AppMockexamTheoryRecord mockexamSpecialRecord = null;
		String currentKey = theoryId+"-"+questionType+"-"+userId+"-"+postId+"-"+questionId;
		String id="";
		if (redisUtils.hasKey(currentKey)){
			mockexamSpecialRecord = (AppMockexamTheoryRecord) redisUtils.get(currentKey);
		}else{
			AppMockexamTheoryRecord asrmodel=new AppMockexamTheoryRecord();
			asrmodel.setTheoryId(theoryId);
			asrmodel.setQuestionType(questionType);
			asrmodel.setUserId(userId);
			asrmodel.setPostId(postId);
			asrmodel.setQuestionId(questionId);
			mockexamSpecialRecord = appMockexamTheoryRecordService.get(asrmodel);
			if(mockexamSpecialRecord!=null){
				redisUtils.set(currentKey,mockexamSpecialRecord);
			}
		}
		if(mockexamSpecialRecord!=null){
			id = mockexamSpecialRecord.getId();
		}
   		 if(StringUtils.isNotBlank(objAnswer)) {
   			//先判断长度
   			boolean sco=AnswerUtils.calculation(objAnswer, answerId);
		    if(sco) {
				Double score = answerObj.getScore();
			    entity.setScore(new BigDecimal(score));
			}else {
				entity.setScore(new BigDecimal(0.0));
			}
   		 }
   		 
   		 if(StringUtils.isNotBlank(id)){
   			entity.setId(id);
   			appMockexamTheoryRecordService.update(entity);
   		 }else{
   			appMockexamTheoryRecordService.save(entity);
   		 }
   		 JSONObject obj=JSONObject.parseObject(JsonMapper.toJson(entity));
   		 AppController.renderSuccessObject(response, obj, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 单选题
	 * @param entity
	 * @param request
	 * @param response
	 */
	@RequestMapping(value ="add")
	public void add(AppMockexamTheoryRecord entity, HttpServletRequest request,HttpServletResponse response){
		String theoryId = entity.getTheoryId();
		if(StringUtils.isBlank(theoryId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"理论标识不存在");
			return;
		}
		String questionId = entity.getQuestionId();
		if(StringUtils.isBlank(questionId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"问题标识不存在");
			return;
		}
		Integer questionType = entity.getQuestionType();
		if(questionType==null){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"问题类型不存在");
			return;
		}
		String userId = entity.getUserId();
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"用户信息");
			return;
		}
		String answerId = entity.getAnswerId();
		if(StringUtils.isBlank(answerId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"答案信息");
			return;
		}
		AppMockexamTheoryRecord model=new AppMockexamTheoryRecord();
		model.setTheoryId(theoryId);
		model.setQuestionId(questionId);
		model.setUserId(userId);
		List<AppMockexamTheoryRecord> findList = appMockexamTheoryRecordService.findList(model);
		String id="";
		if(findList!=null&&findList.size()>0){
			id=findList.get(0).getId();
		}
		TmockexamTheory answerObj = tmockexamTheoryService.get(answerId);
		String objAnswer = answerObj.getObjAnswer();
		if(StringUtils.isNotBlank(objAnswer)&&objAnswer.equals("1")){
			TmockexamTheory question = tmockexamTheoryService.get(questionId);
			BigDecimal score = question.getScore();
			entity.setScore(score);
		}else{
			entity.setScore(new BigDecimal(0.0));
		}
		if(StringUtils.isNotBlank(id)){
			entity.setId(id);
			appMockexamTheoryRecordService.update(entity);
		}else{
			appMockexamTheoryRecordService.save(entity);
		}
		JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(entity));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	}
	private void updateTheory(){
		TmockexamTheoryUser entity=new TmockexamTheoryUser();
		String theoryId = entity.getTheoryId();
		if(StringUtils.isBlank(theoryId)){
			return;
		}
		String userId=entity.getUserId();
		if(StringUtils.isBlank(userId)){
			return;
		}
		List<TmockexamTheoryUser> findList = tmockexamTheoryUserService.findList(entity);
		entity.setStatus("1");
		tmockexamTheoryUserService.save(entity);
	}
	/**
	 * 清楚数据
	 */
	@RequestMapping(value ="delete")
	public void delete(HttpServletRequest request,HttpServletResponse response){
		String theoryId=request.getParameter("theoryId");
		if(StringUtils.isBlank(theoryId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "理论标识");
			return;
		}
	    String userId=request.getParameter("userId");
        if(StringUtils.isBlank(userId)){
        	AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
	    AppMockexamTheoryRecord entity=new AppMockexamTheoryRecord();
	    entity.setTheoryId(theoryId);
	    entity.setUserId(userId);
	    List<AppMockexamTheoryRecord> findList = appMockexamTheoryRecordService.findList(entity);
	    for(AppMockexamTheoryRecord amtr:findList){
	    	appMockexamTheoryRecordService.delete(amtr);
	    }
	    AppController.renderSuccessObject(response, "", MessageCode.SUCCESS_ACK);
	}
}